﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Kugar.Core.ExtMethod;

namespace Kugar.Tools.SQLHelper.SQLGenerator.EntityT4
{
    
    public partial class SQLServerTableGenerator
    {
        public SQLServerTableGenerator(DbTableStructInfo tableInfo)
        {
            TableInfo = tableInfo;
        }

        public DbTableStructInfo TableInfo { get; }

        public string Namespace { get; set; }

        public string DbContextName { set; get; }

        private DbTableInfo_Column[] GetKeyColumns()
        {
            return TableInfo.Columns.Where(x => x.IsPrimaryKey).ToArrayEx();
        }

        private string FirstLetterLower(string name)
        {
            return T4SQLHelper.FirstLetterLower(name);
        }

        public string ConvertColumnTypeToNetType(DbTableInfo_Column type)
        {
            return T4SQLHelper.ConvertColumnTypeToNetType(type.ValueType,type.IsNullable);
        }

        public string ReplaceFieldNameUnsupportChar(string fieldName)
        {
            return fieldName.Replace('-', '_');
        }

        public string BuildDataAnn(DbTableInfo_Column column)
        {
            var type = ConvertColumnTypeToNetType(column);

            var attr= $"[SugarColumn(IsIdentity = {column.IsAutoInc.ToString().ToLower()},ColumnName =\"{column.Name}\", ColumnDataType = \"{column.ValueType}\", IsNullable = {column.IsNullable.ToString().ToLower()}, IsPrimaryKey = {column.IsPrimaryKey.ToString().ToLower()} {(type== "string" && !type.Contains("text")? $" ,Length = {column.Size}" : "")})]";

            if ((column.ValueType!="ntext" && column.ValueType != "text") && type =="string" && column.Size>0)
            {
                attr = $"{attr}\n\t\t[StringLength({column.Size})]";
            }

            if (!string.IsNullOrWhiteSpace(column.Comment))
            {
                attr= $"{attr}\n\t\t[Description(\"{column.Comment}\"),DisplayName(\"{column.Comment}\")]";
            }

            if (column.IsPrimaryKey)
            {
                attr = $"{attr}\n\t\t[Key]";
            }

            return attr;
        }

        
    }
    
}
